<?php

require("../function/util.php");

$gallery_id 			= $_POST['gallery_id'];
$gallery_image_old 		= $_POST['gallery_image_old'];

$gallery_type 			= addslashes($_POST['gallery_type']);
$gallery_weight 		= addslashes($_POST['gallery_weight']);
$gallery_topic 			= addslashes($_POST['gallery_topic']);
$gallery_detail 		= addslashes($_POST['gallery_detail']);
$gallery_status 		= $_POST['gallery_status'];
$current_time 			= time();

$gallery_image_type 			= explode('.' , $_FILES["gallery_image"]["name"]);

$gallery_image_filename 		= "gallery_image_" . $current_time . "." . $gallery_image_type[1];

$err_msg = "";

if (strlen(trim($gallery_type)) == 0) {
    $err_msg .= "Please fill in Class<br/>";
}

if (strlen(trim($gallery_weight)) == 0) {
    $err_msg .= "Please fill in Weight<br/>";
}

if (strlen(trim($gallery_topic)) == 0) {
    $err_msg .= "Please fill in Topic<br/>";
}
if (strlen(trim($gallery_detail)) == 0) {
    $err_msg .= "Please fill in Detail<br/>";
}

if ($_FILES["gallery_image"]["size"] > 0)
{
    if ( !( $_FILES["gallery_image"]["type"] == "image/jpeg" || $_FILES["gallery_image"]["type"] == "image/pjpeg" || $_FILES["gallery_image"]["type"] == "image/png" || $_FILES["gallery_image"]["type"] == "image/gif" ) ) 
	{
        $err_msg .= "Image file must be jpeg, png or gif<br/>";
    }

    if ( !( $_FILES["gallery_image"]["size"] < 2000000 ) )
	{
        $err_msg .= "Image file is too large<br/>";
    }

    if ( $_FILES["gallery_image"]["error"] > 0 )
	{
        $err_msg .= "Image File Error!<br/>";
    }
} else
{
       $gallery_image_filename = $gallery_image_old;
}

if (strlen($err_msg) == 0) 
{
	$sql = "UPDATE gallery
			SET gallery_type 			='$gallery_type',
				gallery_weight 			='$gallery_weight',
				gallery_image 			='$gallery_image_filename',
				gallery_topic 			='$gallery_topic',
				gallery_detail 			='$gallery_detail',
				gallery_status 			='$gallery_status'
			WHERE gallery_id = '$gallery_id'";
	if(runSQL($sql))
	{

		if ( $_FILES["gallery_image"]["size"] > 0 )
		{
			$thumbfile = FILE_LOCATION . THUMB_LOCATION . "gallery/" . "gallery_image_" . $current_time . "." . $gallery_image_type[1];
			if (move_uploaded_file($_FILES["gallery_image"]["tmp_name"], $thumbfile)) 
			{
				$small_thumbnail_image = 1;
			}
		}
?>
		<script type="text/javascript">
			alert("Edit Picture Successful!");
				top.document.getElementById('cancel_button').click();
		</script>
<?php
	} else
	{
?>
		<script type="text/javascript">
			alert("Edit Picture can't not be performed right now!");
		</script>
<?php
	}
} else
{
?>
    <script type="text/javascript">
        top.document.getElementById('error').innerHTML = "<?= $err_msg ?>";
    </script>
<?php
}
?>